package other.system.client.oa.submit;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.rkhd.platform.sdk.data.model.SporadicProcurement__c;
import com.rkhd.platform.sdk.exception.ApiEntityServiceException;
import com.rkhd.platform.sdk.exception.ScriptBusinessException;
import com.rkhd.platform.sdk.log.Logger;
import com.rkhd.platform.sdk.log.LoggerFactory;
import com.rkhd.platform.sdk.model.QueryResult;
import com.rkhd.platform.sdk.service.XoqlService;
import com.rkhd.platform.sdk.task.FutureTask;
import org.apache.commons.lang.StringUtils;
import other.system.client.util.HCXObjectService;
import other.system.client.util.ResultBody;
import other.system.client.util.TfReturnMsgTools;

import java.util.List;
import java.util.Objects;

/**
 * @Description: 提交零星采购模块
 * @Author: 黎炎松
 * @Date: 2024/7/9 17:31
 */
public class SubmitSporadicPurchase extends SubmitSuper {
    private static HCXObjectService hcxObjectService = new HCXObjectService();

    private static XoqlService xoqlService = XoqlService.instance();

    private static final String LOGGER_MSG = "推送零星采购审批数据到OA ==> ";

    private static final Logger logger = LoggerFactory.getLogger();


    public static void main(String[] args) throws ApiEntityServiceException {
        SubmitSporadicPurchase submitSporadicPurchase = new SubmitSporadicPurchase();

        // 需切换测试环境进行测试，正式环境发送会导致他们的人员账号收到审批提醒
        submitSporadicPurchase.pushSporadicPurchaseToOA(3454418189556374L);
    }

    /**
     * 提交零星采购数据到OA审批  sporadicProcurement__c
     * @param
     * @return
     */
    public String pushSporadicPurchaseToOA(Long sporadicPurchaseId) {
        try {
            logger.info(LOGGER_MSG + "处理开始: " + sporadicPurchaseId);

            // 获取基本信息
            String sql = "select id,name,applicationNumber__c,contractPartyA__c.name partyName,contractPartyB__c,projectCode__c,projectName__c,budgetRange__c,contractAmountU__c,contractAmountT__c,taxRate__c," +
                    "customItem6__c,paymentTerms__c,contractClause__c,otherRemarks__c,projectLink__c,attachments__c,oaApprovalId__c,oaApprovalStatus__c," +
                    "countersignNode__c.LoginName__c oaAccount,countersignNode__c.personalEmail oaEmail,ownerId.LoginName__c ownerOaAccount,ownerId.personalEmail ownerOaEmail " +
                    " from sporadicProcurement__c where id = " + sporadicPurchaseId;
            QueryResult<JSONObject> query = xoqlService.query(sql, true);
            List<JSONObject> records = query.getRecords();
            if (records.size() <= 0) {
                logger.error(LOGGER_MSG + "获取零星采购数据异常");
                return TfReturnMsgTools.getFailResult("获取零星采购数据异常:" + query.getErrorMessage());
            }

            // 获取字段信息
            JSONObject purchase = records.get(0);
            String name = purchase.getString("name");
            String oaApprovalId = purchase.getString("oaApprovalId__c");
            String oaApprovalStatus = getOptionStr(purchase.getJSONArray("oaApprovalStatus__c"));
            // 如果是 作废 状态，则重新提交
            if (Objects.equals(oaApprovalStatus, "作废")) {
                oaApprovalId = "";
            }


            // 拼接表单的数据
            JSONObject formObject = new JSONObject();
            formObject.put("fd_37b1e89e98e5d2", name); // 合同名称

            formObject.put("fd_3cf64d2afb038a", purchase.getString("applicationNumber__c")); // 申请单编号
            formObject.put("fd_37b1e8b187282a", purchase.getString("partyName")); // 合同甲方
            formObject.put("fd_37b1e8b3b79336", purchase.getString("contractPartyB__c")); // 合同乙方
            formObject.put("fd_37b1ec128ea90e", purchase.getString("projectCode__c")); // 项目编码
            formObject.put("fd_3cf64c54a002e0", purchase.getString("projectName__c")); // 项目名称

            formObject.put("fd_37b1ec04e788ee", getOptionStr(purchase.getJSONArray("budgetRange__c")).equals("是") ? 1 : 2 ); // 是否预算范围内
            formObject.put("fd_37b1e9b72f9eca", purchase.getString("contractAmountU__c")); // 合同金额（未税）
            formObject.put("fd_380dd397ae7c2e", purchase.getString("contractAmountT__c")); // 合同金额（含税）
            formObject.put("fd_37b1e9c5fb37b2", purchase.getDouble("taxRate__c") * 100); // 税率%
            formObject.put("fd_37b1eb0df6af16", getOptionStr(purchase.getJSONArray("customItem6__c"))); // 合同类型

            formObject.put("fd_37b1eaf102db0a", purchase.getString("paymentTerms__c")); // 付款条件
            formObject.put("fd_37b1eaee7d0884", purchase.getString("contractClause__c")); // 合同关键条款

            formObject.put("fd_37b1eaea2a9930", purchase.getString("otherRemarks__c")); // 其他备注
            formObject.put("fd_37b1ead32928bc", purchase.getString("projectLink__c")); // 立项链接
            formObject.put("fd_3b0c035919f062", getOaAccount(purchase, 1)); // 加签
            logger.info(LOGGER_MSG + "formObject: " + formObject);

            // 获取所有人的OA账号 发送请求
            JSONObject ownerOaAccount = getOaAccount(purchase, 2);
            ResultBody resultBody = pushReqToOa("purchase", name, oaApprovalId, ownerOaAccount, formObject,null);
            logger.info(LOGGER_MSG + "resultBody: " + resultBody);
            if (!Objects.equals(resultBody.getCode(), "200")) {
                logger.error(LOGGER_MSG + "推送零星采购类数据到OA异常: " + resultBody.getMessage());
                return TfReturnMsgTools.getFailResult("推送零星采购类数据到OA异常:" + resultBody.getMessage());
            }

            // 返回的 id 进行保存
            String newOAId = resultBody.getResult().toString();
            SporadicProcurement__c sporadicProcurement = new SporadicProcurement__c();
            sporadicProcurement.setId(sporadicPurchaseId);
            sporadicProcurement.setOaApprovalId__c(newOAId);
            sporadicProcurement.setOaApprovalStatus__c(1);
            sporadicProcurement.setLockStatus(2);
            Boolean update = hcxObjectService.update(sporadicProcurement);
            logger.info(LOGGER_MSG + "update: " + update);

            // 撤回后重新提交需要修改OA的数据状态为 已提交
            if (StringUtils.isNotBlank(oaApprovalId) && (Objects.equals(oaApprovalStatus, "撤回") || Objects.equals(oaApprovalStatus, "驳回"))) {
                resubmitApprovalData(oaApprovalId, ownerOaAccount);
            }

            // 单独的方法更新附件
            JSONArray fileList = purchase.getJSONArray("attachments__c"); // 附件
            UploadOAFile.syncUoloadFile(newOAId, fileKeyMap.get("purchase"), fileList);


            logger.info(LOGGER_MSG + "提交成功");
            return TfReturnMsgTools.getSuccessResult("提交成功");
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(LOGGER_MSG + "处理异常: " + e.getMessage());
            return TfReturnMsgTools.getFailResult("推送异常:" + e.getMessage());
        }
    }

}
